/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxsub(TreeNode* root, int& max_sum){

        int max_left=0, max_right=0;
        if(root->left){
            max_left = max(maxsub(root->left, max_sum), max_left);
        }
        if(root->right){
            max_right = max(maxsub(root->right, max_sum), max_right);
        }
        max_sum = max(max_sum, root->val+max_right+max_left);

        return root->val + max(max_left, max_right);
    }

    int maxPathSum(TreeNode* root) {
        int max_sum = 0;
        maxsub(root, max_sum);

        return max_sum;
    }
};